package com.ruoyi.business.controller;

import com.ruoyi.business.payment.service.ITRegisterPaymentOrderService;
import com.ruoyi.business.payment.vo.*;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.constant.RoleConstants;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysRole;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.core.page.TableDataInfo;

import javax.servlet.http.HttpServletResponse;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.List;

/**
 * 预支付订单信息Controller
 *
 * @author Tellsea
 * @date 2025-06-22
 */
@Api(tags = "预支付订单信息Controller")
@RestController
@RequestMapping("/business/registerPaymentOrder")
@RequiredArgsConstructor(onConstructor_ = @Autowired)
public class TRegisterPaymentOrderController extends BaseController {

    private final ITRegisterPaymentOrderService tRegisterPaymentOrderService;

    @ApiOperation("查询预支付订单信息列表")
    @PostMapping("/list")
    public TableDataInfo<TRegisterPaymentOrderDto> list(@RequestBody TRegisterPaymentOrderVo entity) {

        setUserRoleAuth(entity);

        return tRegisterPaymentOrderService.queryList(entity);
    }


    @ApiOperation("查询预支付订单信息所有列表")
    @PostMapping("/listAll")
    public AjaxResult listAll(@RequestBody TRegisterPaymentOrderVo entity) {

        setUserRoleAuth(entity);

        return AjaxResult.success("查询成功", tRegisterPaymentOrderService.queryAll(entity));
    }

    @ApiOperation("进修科室统计列表")
    @PostMapping("/queryByDept")
    public TableDataInfo<TRegisterPaymentOrderDeptDto> queryByDept(@RequestBody TRegisterPaymentOrderVo entity) {

        setUserRoleAuth(entity);

        return tRegisterPaymentOrderService.queryByDept(entity);
    }

    @ApiOperation("订单筛选统计接口")
    @PostMapping("/queryByStat")
    public AjaxResult queryByStat(@RequestBody @Validated TRegisterPaymentOrderVo entity) {

        setUserRoleAuth(entity);

        return AjaxResult.success("查询成功", tRegisterPaymentOrderService.queryByStat(entity));
    }

    @ApiOperation("导出预支付订单信息列表")
    @PreAuthorize("@ss.hasPermi('business:registerPaymentOrder:export')")
    @Log(title = "预支付订单信息", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, TRegisterPaymentOrderVo entity) {

        setUserRoleAuth(entity);

        List<TRegisterPaymentOrderDto> list = tRegisterPaymentOrderService.queryAll(entity);
        ExcelUtil<TRegisterPaymentOrderDto> util = new ExcelUtil<>(TRegisterPaymentOrderDto.class);
        util.exportExcel(response, list, "预支付订单信息数据");
    }

    @ApiOperation("获取预支付订单信息详细信息")
    @PostMapping(value = "/getInfo")
    public AjaxResult getInfo(@RequestBody @Validated TRegisterPaymentOrderVo entity) {
        setUserRoleAuth(entity);
        return AjaxResult.success("查询成功", tRegisterPaymentOrderService.queryById(entity.getOrderId()));
    }

    @ApiOperation("获取预支付订单信息详细信息【通过registerID】")
    @PostMapping(value = "/getInfoByRegisterId")
    public AjaxResult getInfoByRegisterId(@RequestBody @Validated TRegisterPaymentOrderVo entity) {
        setUserRoleAuth(entity);
        TRegisterPaymentOrderDto paymentOrderDto = tRegisterPaymentOrderService.queryByRegisterId(entity.getRegisterId());
        if(paymentOrderDto==null){
            return AjaxResult.error("学员支付订单不存在");
        }
        return AjaxResult.success("查询成功", paymentOrderDto);
    }

    @ApiOperation("新增预支付订单信息")
    @Log(title = "新增预支付订单信息", businessType = BusinessType.INSERT)
    @PostMapping("/createPreOrder")
    public AjaxResult createPreOrder(@RequestBody @Validated TRegisterPaymentOrderVo entity) throws Exception {
        Long orderId = tRegisterPaymentOrderService.createPrePaymentOrder(entity.getRegisterId());
        return AjaxResult.success("预下单成功", orderId);
    }

    @ApiOperation("关闭订单")
    @Log(title = "关闭订单", businessType = BusinessType.UPDATE)
    @PostMapping("/closeOrder")
    public AjaxResult closeOrder(@RequestBody @Validated TRegisterPaymentOrderVo entity) throws Exception {
        tRegisterPaymentOrderService.closeOrder(entity.getOrderId());
        return AjaxResult.success("关闭订单成功", entity.getOrderId());
    }

    @ApiOperation("添加退款申请")
    @Log(title = "添加退款申请", businessType = BusinessType.UPDATE)
    @PostMapping("/addRefundApply")
    public AjaxResult addRefundApply(@RequestBody @Validated TRegisterRefundApplyDto dto) throws ParseException {
        tRegisterPaymentOrderService.addRefundApply(dto.getOrderId(), dto.getRefundAmount(), dto.getRefundReason());
        return AjaxResult.success("退款申请成功,请关注后续的审批");
    }

    @ApiOperation("退款流程审批")
    @Log(title = "退款流程审批", businessType = BusinessType.UPDATE)
    @PostMapping("/processApproval")
    public AjaxResult processApproval(@RequestBody @Validated TRegisterProcessApprovalDto dto) throws Exception {
        tRegisterPaymentOrderService.processApproval(dto.getApprovalId(), dto.getStatus(), dto.getOpinion());
        return AjaxResult.success("审批完成");
    }

    /**
     * 设置用户角色权限
     * @param entity 实体id
     */
    private static void setUserRoleAuth(TRegisterPaymentOrderVo entity) {
        SysUser loginUser = SecurityUtils.getLoginUser().getUser();
        entity.setUserId(loginUser.getUserId());
        if(loginUser.getRoles()!=null){
            List<String> roleKeyList = new ArrayList<>();
            for (SysRole role : loginUser.getRoles()) {
                roleKeyList.add(role.getRoleKey());
            }
            if(roleKeyList.contains(RoleConstants.STUDENT.getRoleKey())){
                entity.setUserRoleKey(RoleConstants.STUDENT.getRoleKey());
            } else if(roleKeyList.contains(RoleConstants.ADMIN.getRoleKey())){
                entity.setUserRoleKey(RoleConstants.ADMIN.getRoleKey());
            } else {
                entity.setUserRoleKey(RoleConstants.DEPT_MANAGE.getRoleKey());
            }
        }
    }

}
